package com.hatricks.is.algorithm.binarysearch;

/**
 * @packageName: com.hatricks.is.algorithm.binarysearch
 * @className: BinarySearch
 * @author: yanyuhui y568821795@outlook.com
 * @date: 2024-11-18 10:35
 * @description:
 */
public class BinarySearch {

    public static int binarySearch(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;
        while (left <= right) {
            int mid = left + (right - left) / 2;
            if (nums[mid] == target) {
                return mid;
            } else if (nums[mid] < target) {
                // log（n） 的关键
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return -1;
    }


    public static void main(String[] args) {
        int[] nums1 = {1, 2, 3, 4, 5};
        int target1 = 3;
        System.out.println(binarySearch(nums1, target1));  // 输出: 2

        int[] nums2 = {1, 2, 3, 5, 8};
        int target2 = 8;
        System.out.println(binarySearch(nums2, target2));  // 输出: 4

        int[] nums3 = {-1, 0, 3, 5, 9, 12};
        int target3 = 9;
        System.out.println(binarySearch(nums3, target3));  // 输出: 4

        int[] nums4 = {-1, 0, 3, 5, 9, 12};
        int target4 = 2;
        System.out.println(binarySearch(nums4, target4));  // 输出: -1
    }
}
